package randomthoughts.dp;

/**leetCode 72
 * @author tongchen
 * @create 2023-05-09 22:10
 */
public class EditDistance {
    //dp数组下标及其含义dp[i][j]代表以i-1和j-1结尾数组相同时需要的操作数
    //递推公式：if(i-1==j-1) dp[i][j]=min(dp[i-1][j-1])
    //if(i-1!=j-1) dp[i][j]=min(dp[i][j-1]+1(删除一个字符串的元素或者) dp[i-1][j]+1,dp[i-1][j-1]+1)
    //初始化dp[i][0]=i;dp[0][j]=j
    //遍历顺序：从前往后遍历
    public int minDistance(String word1, String word2) {
        //创建dp数组
        int[][]dp=new int[word1.length()+1][word2.length()+1];
        //初始化
        for(int i=0;i<=word1.length();++i){
            dp[i][0]=i;
        }
        for(int j=0;j<=word2.length();++j){
            dp[0][j]=j;
        }
        //进行遍历
        for(int i=1;i<=word1.length();++i){
            for(int j=1;j<=word2.length();++j){
                if(word1.charAt(i-1)==word2.charAt(j-1)){
                    dp[i][j]=dp[i-1][j-1];
                }else{
                    dp[i][j]=Math.min(dp[i-1][j-1]+1,Math.min(dp[i][j-1]+1,dp[i-1][j]+1));
                }
            }
        }
        return dp[word1.length()][word2.length()];
    }
}

